#pragma onec
#include <iostream>
#include <vector>
#include <string>
#include "Inetaddr.hpp"
using namespace std;
#include <sys/types.h>
#include <sys/socket.h>


class MessageRoute
{
private:
    bool isexists(const InetAddr& addr)
    {
        for(auto e:_online_user)
        {
            if(e == addr) return true;
        }
        return false;
    }   
public:
    MessageRoute()
    {

    }
    
    void addUser(const InetAddr& addr)
    {
        if(isexists(addr)) return;
        _online_user.push_back(addr);
    }

    void DelUser(const InetAddr& addr)
    {
        for(auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
        {
           if(*iter == addr)
           {
                _online_user.erase(iter);
                break;
           }
        }
    }

    void Route(int sockfd,const string messages,const InetAddr who)
    {
        addUser(who);

        if(messages == "Q" || messages == "QUIT")
        {
            DelUser(who);
        }

        for(auto user: _online_user)
        {
            sockaddr_in addr = user.Addr();
  
            sendto(sockfd,messages.c_str(),messages.size(),0,(sockaddr*)&addr,sizeof(addr));
        }
    }

    ~MessageRoute()
    {

    }
private:
    vector<InetAddr> _online_user;
};


